#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"log.hpp"
#include"Common.hpp"    

using namespace LogModule;

//./client 127.0.0.1 8080
int main(int argc, char* argv[])
{
    ENABLE_CONSOLE_LOG();

    if(argc!= 3)
    {
        std::cout<<"Uasge:"<<argv[0]<<" ip port"<<std::endl;
        return 1;
    }
    std::string server_ip =argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        LOG(LogLevel::ERROR)<<"create socket failed";
        return 2;
    }

    struct sockaddr_in server_addr; 
    server_addr.sin_family = AF_INET;   
    server_addr.sin_port = htons(server_port);  
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str()); 

    
    int n = ::connect(sockfd ,CONV(&server_addr) , sizeof(server_addr));
    if(n < 0)
    {
        LOG(LogLevel::ERROR)<<"connect failed"; 
        return 3;
    }

    //Echo Client
    std::string message;
    while(true)
    {
        char inbuffer[1024];
        std::cout<<"input message:";
        std::getline(std::cin ,message);

        //发给服务器
        int n2 = write(sockfd, message.c_str() , message.size());
        if(n2 > 0)
        {
            int m = read(sockfd, inbuffer ,sizeof(inbuffer)-1);
            if(m >0)
            {
                inbuffer[m] = 0;
                std::cout<<inbuffer<<std::endl;

            }
            else
            {
                break;
            }
        }
        else
            break;
    }

    ::close(sockfd);
    return 0;
}